<?php

namespace lico\Tool;

class Cache
{

    protected static $type = 'redis';
    protected static $handler;

    public function __construct($type = '')
    {
        $type && self::$type = $type;
    }

    /**
     * 获取连接主体
     */
    public function getHandler($long = false)
    {
        if (is_null(self::$handler)) {
            $nameSpace = __CLASS__.'\\'.ucfirst(strtolower(self::$type));
            $handler = new $nameSpace();
            self::$handler = $handler->connect(['pconnnect'=>$long]);
        }
        return self::$handler;
    }

    /**
     * 队列
     */
    public function queue()
    {
        //存在写入
        $exist = self::$handler->exists('num');
        if (!$exist) {
            self::$handler->setnx('num', 0);
        }
        $queue = self::$handler->lrange('queue', 0, -1);
        if (count($queue) < 20) {
            self::$handler
            ->multi()
            ->incrBy('num', 1)
            // ->decrBy('num', 1)
            ->exec()
            ;

            $num = self::$handler->get('num');

            self::$handler
            // ->multi()
            ->lPush('queue', $num)
            // ->exec()
            ;
        }

        p(self::$handler->lrange('queue', 0, -1));
    }
}
